package org.springblade.upgrade.constant;

import cn.hutool.json.JSONUtil;
import org.springblade.modules.system.domain.BladeFile;
import org.springblade.upgrade.log.entity.PackageLog;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传工具类
 */
public class PackageUploadUtil {
    /**
     * 去掉多余字符
     *
     * @param file
     * @return
     */
    public static String trim(String file) {
        if (file == null) {
            return "";
        }
        String t = file.replace("\\", File.separator);
        while (t.indexOf("//") > 0) {
            t = t.replace("//", File.separator);
        }
        return t;
    }


    /**
     * 取得文件
     *
     * @param fileInfo
     */
    public static File getFile(PackageLog fileInfo) {
        String tarFileName = fileInfo.getDomainUrl() + File.separator + fileInfo.getSaveAddress();
        File file = new File(trim(tarFileName));
        return file;
    }

    /**
     * 格式化路径
     *
     * @param inSaveAddress
     * @return
     */
    public static String formatAddress(String inSaveAddress) {
        String saveAddress = inSaveAddress;
        saveAddress = saveAddress.replace("-", "");
        saveAddress = saveAddress.replace(":", "");
        saveAddress = saveAddress.replace(".", "");
        saveAddress = saveAddress.replace(" ", "");
        return saveAddress.trim();
    }


    /**
     * 转换
     *
     * @param attach
     * @return
     */
    public static BladeFile convert(PackageLog attach) {
        if (attach == null) {
            return null;
        }
        BladeFile res = new BladeFile();
        res.setAttachId(attach.getId());
        res.setName(attach.getName());
        res.setOriginalName(attach.getOriginalName());
        res.setLink(attach.getLink());
        res.setDomain(attach.getDomainUrl());
        return res;
    }


    /**
     * 错误返回结果
     *
     * @param response: 响应
     * @param s：结果
     * @throws IOException 异常
     */
    public static void buildResponse(HttpServletResponse response, String s) throws IOException {
        Map<String, String> resMap = new HashMap<>(0);
        resMap.put("code", "405");
        resMap.put("message", s);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJsonStr(resMap));
        writer.flush();
        writer.close();
    }

}
